﻿angular.module('app')
    .directive("taskBox", ['$document', 'WorkContextSrv', 'TaskSrv', '$timeout', '$window', '$rootScope',
        function ($document, workContextSrv, taskSrv, $timeout, $window, $rootScope) {
            return {
                scope: {
                    task: '='
                },
                replace: true,
                restrict: 'E',
                templateUrl: 'scripts/app/views/task/box.html',
                link: function (scope, element, attrs) {
                    var postUrl = 'api/topics';
                    var currentUser = workContextSrv.getCurrentUser();
                    var username = currentUser.userName;

                    //check assign status
                    function checkAssigned(t) {
                        return typeof t.task != 'undefined' && currentUser.userName == t.task.acceptedBy;
                    }

                    scope.taskComment = {
                        onSubmitting: false,
                        loadingComments: false,
                        onViewDetail: false,
                        showMessage: false,
                        hasErrors: false,
                        errorMessage: ''
                    };

                    scope.taskDetail = {};

                    //collapse if click outside task box
                    $document.bind('click', function (e) {
                        //hide the message
                        scope.taskComment.showMessage = false;

                        //stop collapse comment boxs when user click to comments box, task detail is openning,
                        if (!angular.element(e.target).parents(".task-message").length > 0 && !angular.element(e.target).parents(".task-comments").length > 0 && !angular.element(e.target).hasClass('task-box-loading-comments') && !angular.element(e.target).parent("#taskdetailcontrol").length > 0 && !angular.element("#iframeaction").length > 0) {
                            angular.element(".task-comments").hide();
                            angular.element(".task-comments").removeClass("slidein");
                        }
                    });

                    //expand function
                    scope.expandTaskBox = function ($event, tp) {
                        //hide the message
                        scope.taskComment.showMessage = false;

                        //stop expanding when user click to loading overlay, attach files and complete button
                        if (angular.element($event.target).hasClass('task-box-loading-comments') || angular.element($event.target).hasClass('btnsavetaskfile') || angular.element($event.target).hasClass('lbassigned')) {
                            return;
                        }

                        //if task comments box has expanded
                        if (angular.element(element).find(".task-comments").hasClass("slidein")) {
                            //hide task comments box
                            angular.element(element).find(".task-comments").hide();

                            //remove 'slidein' class from comments box
                            angular.element(element).find(".task-comments").removeClass("slidein");
                        } else {
                            //on loadingComment state
                            scope.taskComment.loadingComments = true;

                            //post get task by oid request
                            taskSrv.getTaskByToid(tp.task.taskOid).success(function (dt) {
                                //bind taskdetail to model
                                scope.taskDetail = dt;

                                //bind current index of task in list
                                scope.taskDetail.index = attrs.tindex;

                                //off loadingComment state
                                scope.taskComment.loadingComments = false;

                                //show comments box
                                angular.element(element).find(".task-comments").show();

                                //add 'slidein' class to comments box
                                angular.element(element).find(".task-comments").addClass("slidein");
                            });
                            //taskSrv.getCommentsForTask(tp.task.workflowOid).success(function (dt) {
                            //    scope.taskComment.comments = dt;
                            //    scope.taskComment.loadingComments = false;
                            //    angular.element(element).find(".task-comments").slideDown();
                            //    angular.element(element).find(".task-comments").addClass("slidein");
                            //});
                        }
                    };

                    //open task detail popup
                    scope.viewTaskDetail = function (t, idx) {
                        //on submitting state
                        scope.taskComment.onSubmitting = true;

                        scope.taskComment.hasErrors = false;

                        //hide the message
                        scope.taskComment.showMessage = false;

                        //scroll to top when view detail
                        t.scrollTop = angular.element($window).scrollTop();

                        //post assign request
                        taskSrv.taskOperation(t.task.taskOid, 'assign', currentUser.userName, '', '')
                            .success(function (dt, st) {
                                if (dt === '') {
                                    //open task detail
                                    scope.$emit("openTaskDetail", t);

                                    //set 'Assigned' state to current task
                                    scope.taskDetail.task.isAssigned = true;
                                    scope.task.task.isAssigned = true;
                                } else {
                                    //alert erro message
                                    alert(dt.message);
                                }
                                //off submitting state
                                scope.taskComment.onSubmitting = false;
                            })
                            .error(function () {
                                //off submitting state
                                scope.taskComment.onSubmitting = false;
                            });

                    };

                    //check assign status
                    scope.isTaskAssignedToMe = function (t) {
                        return checkAssigned(t);
                    };

                    //assign task to me
                    //scope.assignTask = function (t) {
                    //    scope.taskComment.hasErrors = false;
                    //    scope.taskComment.onSubmitting = true;
                    //    var operation = 'assign';
                    //    taskSrv.taskOperation(t.task.taskOid, operation, currentUser.userName).success(function (dt, st) {
                    //        if (dt === '') {
                    //            scope.taskDetail.task.isAssigned = true;
                    //            scope.task.task.isAssigned = true;
                    //        } else {
                    //            scope.taskComment.hasErrors = true;
                    //            scope.taskComment.errorMessage = dt.message;
                    //        }
                    //        scope.taskComment.onSubmitting = false;
                    //    }).error(function () {
                    //        scope.taskComment.onSubmitting = false;
                    //    });
                    //};

                    //give back task
                    scope.giveBackTask = function (t) {

                        scope.taskComment.hasErrors = false;
                        //hide the message
                        scope.taskComment.showMessage = false;

                        //on submitting state
                        scope.taskComment.onSubmitting = true;

                        //operation
                        var operation = 'giveback';

                        //post giveback request
                        taskSrv.taskOperation(t.task.taskOid, operation, currentUser.userName, '', '')
                            .success(function (dt, st) {
                                //show the message
                                scope.taskComment.showMessage = true;
                                if (dt === '') {
                                    //set 'Assigned' state to current task
                                    scope.taskDetail.task.isAssigned = false;
                                    scope.task.task.isAssigned = false;

                                    //bind the success message
                                    scope.taskComment.errorMessage = "Giving back task successful";
                                } else {
                                    //show the error message
                                    scope.taskComment.hasErrors = true;

                                    //bind the error message
                                    scope.taskComment.errorMessage = dt.message;
                                }

                                //update user stat
                                $rootScope.$broadcast("loadUserStat");

                                //off submitting state
                                scope.taskComment.onSubmitting = false;

                                //Re-update task counter
                                $rootScope.$broadcast("getTaskCount", false);
                            })
                            .error(function (dt, st) {
                                if (st !== 401) {
                                    alert(dt);
                                }
                                //off submitting state
                                scope.taskComment.onSubmitting = false;
                            });
                    };

                    //complete task
                    scope.completeTask = function (t) {
                        //on loadingComment state
                        scope.taskComment.loadingComments = true;

                        //operation
                        var operation = 'approve';

                        //post approve request
                        taskSrv.taskOperation(t.task.taskOid, operation, currentUser.userName, t.task.defaultResult, 'quick run task')
                            .success(function (dt, st) {
                                if (dt === '') {

                                    //remove task from list
                                    scope.$emit("removeTaskFromList", attrs.tindex);

                                    //show the success message
                                    jQuery("<div id='footer-notification' class='alert alert-success no-margin'><i class='fa-fw fa fa-check'></i> Completing task successful</div>").appendTo(jQuery("body")).delay(1500).fadeOut();
                                } else {
                                    //show the error message
                                    jQuery("<div id='footer-notification' class='alert alert-danger no-margin'><i class='fa-fw fa fa-times'></i> " + dt.message + "</div>").appendTo(jQuery("body")).delay(1500).fadeOut();
                                }

                                //update user stat
                                $rootScope.$broadcast("loadUserStat");

                                //off loadingComment state
                                scope.taskComment.loadingComments = false;

                                //Re-update task counter
                                //$rootScope.$broadcast("getTaskCount", false);
                                $rootScope.$broadcast("decreaseTaskCount", 1);
                            })
                            .error(function (dt, st) {
                                if (st !== 401) {
                                    alert("Error");
                                }

                                //off loadingComment state
                                scope.taskComment.loadingComments = false;
                            });
                    };
                }
            };
        }
    ])
    .directive("taskCompletedCount", ['WorkContextSrv', '$interval', 'UserSrv', '$state', 'webStorage', '$timeout', '$log', '$rootScope', function (workContextSrv, $interval, userSrv, $state, webStorage, $timeout, $log, $rootScope) {
        return {
            restrict: 'E',
            scope: true,
            replace: true,
            templateUrl: 'scripts/app/views/task/taskcompleted.count.html',
            link: function (scope) {
                $timeout(function () {
                    getUserStats();
                }, 1000);

                $rootScope.$on("reCountUserStat", function () {
                    getUserStats();
                });

                //scope.taskCompleted = {
                //    count: 0,
                //    value: '',
                //    tooltip: ''
                //};

                function getUserStats() {
                    var dt = webStorage.get("user.stat");

                    //get task completed value
                    var taskCompletedValue = [];
                    if (dt != null) {
                        angular.forEach(dt.tasksCompleted, function (value, key) {
                            taskCompletedValue.push(value.counter);
                        });
                        //get task completed tooltip
                        var taskCompletedTooltip = [];
                        angular.forEach(dt.tasksCompleted, function (value, key) {
                            taskCompletedTooltip.push(value.date);
                        });
                        //Task Completed
                        scope.taskCompleted = {
                            count: dt.tasksCompletedCount,
                            value: taskCompletedValue.join(','),
                            tooltip: taskCompletedTooltip.join(',')
                        };
                    }
                    
                }

                //scope.$watch(webStorage.get("user.stat").tasksCompletedCount, function () {
                //    //$log.info("Updating user stats: TaskCompleted");
                //    getUserStats();
                //});
            }
        };
    }])
    .directive("taskToDoCount", ['WorkContextSrv', '$interval', 'UserSrv', '$state', 'webStorage', '$timeout', '$log', '$rootScope', function (workContextSrv, $interval, userSrv, $state, webStorage, $timeout, $log, $rootScope) {
        return {
            restrict: 'E',
            scope: true,
            replace: true,
            templateUrl: 'scripts/app/views/task/tasktodo.count.html',
            link: function (scope) {
                $timeout(function () {
                    getUserStats();
                }, 1000);

                $rootScope.$on("reCountUserStat", function () {
                    getUserStats();
                });

                //scope.taskToDo = {
                //    count: 0,
                //    value: '',
                //    tooltip: ''
                //};

                function getUserStats() {
                    var dt = webStorage.get("user.stat");
                    //get task to do value
                    var taskToDoValue = [];
                    if (dt != null) {
                        angular.forEach(dt.tasksToDo, function (value, key) {
                            taskToDoValue.push(value.counter);
                        });
                        //get task to do tooltip
                        var taskToDoTooltip = [];
                        angular.forEach(dt.tasksToDo, function (value, key) {
                            taskToDoTooltip.push(value.date);
                        });
                        //Task Completed
                        scope.taskToDo = {
                            count: dt.tasksToDoCount,
                            value: taskToDoValue.join(','),
                            tooltip: taskToDoTooltip.join(',')
                        };
                    }
                }

                //scope.$watch(webStorage.get("user.stat").tasksToDoCount, function () {
                //    //$log.info("Updating user stats: TaskToDo");
                //    getUserStats();
                //});

            }
        };
    }])
    .directive("downloadFileTask", [function () {
        return {
            scope: {
                file: '=',
                taks: '='
            },
            restrict: 'E',
            replace: true,
            controller: ['$scope', function ($scope) {
                $scope.getFileOid = function (file) {
                    return typeof file.documentOid === 'undefined' ? file.oid : file.documentOid;
                };

                //Save file
                //$scope.onDownloading = false;
                //$scope.saveTaskFile = function (file) {
                //    var oid = typeof file.documentOid === 'undefined' ? file.oid : file.documentOid;
                //    //$scope.onDownloading = true;
                //    window.open('api/docs/' + oid);
                //    //topicSrv.downloadAttachment(file.oid).success(function (data, status) {
                //    //    console.log(data);
                //    //    $scope.onDownloading = false;
                //    //}).error(function (dt, st) {
                //    //    $scope.onDownloading = false;
                //    //});
                //};
            }],
            template: '<form method="post" action="ApproveTask/ApproveTask/Document">' +
                '<b class="pull-left col-sm-6 btnsavefile" ng-click="saveTaskFile(file)"><i class="fa fa-file"></i> ' +
                '<input type="submit" name="completeTask" value="{{file.documentName}}" class="linkBoxColor btnsavetaskfile"></b>' +
                '<input length="36" id="TaskOid" name="TaskOid" type="hidden" value="{{task.taskOid}}">' +
                '<input id="DocumentOid" name="DocumentOid" type="hidden" value="{{getFileOid(file)}}">' +
                '</form>'//<b class="pull-left col-sm-6 btnsavefile" ng-click="saveTaskFile(file)"><i class="fa fa-file"></i> {{file.documentName}}</b>
        };
    }])
;